#include "contacts.pb.h"
#include <iostream>
#include <fstream>

int main()
{
    // 将通讯录文件中的所有信息读取出来
    std::ifstream ifs("../contacts.bin", std::ios::in | std::ios::binary);
    c_contacts::Contacts contacts;

    if (!ifs)
    {
        std::cerr << "打开通讯录失败" << std::endl;
        ifs.close();
        return -1;
    }

    //反序列化（将二进制流转化为contacts消息对象）
    if (!contacts.ParseFromIstream(&ifs))
    {
        std::cerr << "读取通讯录失败" << std::endl;
        ifs.close();
        return -2;
    }

    if (contacts.info_size() == 0)
    {
        std::cout << "通讯录为空..." << std::endl;
        ifs.close();
        return 0;
    }

    // 打印到控制台
    for (int i = 0; i < contacts.info_size(); i++)
    {
        std::cout << "----------联系人" << i + 1 << "--------" << std::endl;
        auto info = contacts.info(i);
        std::cout << "姓名: " << info.name() << std::endl;
        std::cout << "年龄: " << info.age() << std::endl;

        for (int j = 0; j < info.phone_size(); j++)
        {
            c_contacts::PeopleInfo_Phone phone = info.phone(j);
            std::cout << "电话" << j << ": " << phone.number() << std::endl;
        }

        //获取未知字段Unknown
        using namespace google::protobuf;

        const auto reflection = info.GetReflection();
        const auto& unknown_fields =  reflection->GetUnknownFields(info);

        for(int j = 0; j < unknown_fields.field_count(); j++)
        {
            const UnknownField& unknown_field = unknown_fields.field(j);
            std::cout << "未知字段" << j+1 << "   字段编号" << unknown_field.number()
            << "   字段类型" << unknown_field.type() << std::endl;

            if(unknown_field.type() == UnknownField::TYPE_VARINT)
            {
                std::cout << "value: " << unknown_field.varint() << std::endl; 
            }
            //...根据不同类型，调用不同get方法
        }
    }
    ifs.close();

    return 0;
}